package com.hibernate.hrm.controller.employee;
import com.hibernate.hrm.dao.UserRepository;
import com.hibernate.hrm.entity.User;
import com.hibernate.hrm.service.login.OperateLogService;
import com.hibernate.hrm.util.ExcelExportUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/employee")
public class EmployeeExportController {

    private final UserRepository userRepository;
    private final OperateLogService operateLogService;

    public EmployeeExportController(UserRepository userRepository, OperateLogService operateLogService  ) {
        this.userRepository = userRepository;
        this.operateLogService = operateLogService;
    }

    @GetMapping("/export")
    public void exportEmployeesToExcel(HttpServletResponse response,
                                       @AuthenticationPrincipal User currentUser,
                                       HttpServletRequest request) throws IOException {
        System.out.println("\n==================================");
        System.out.println("||                              ||");
        System.out.println("||        开始导出            ||");
        System.out.println("||                              ||");
        System.out.println("==================================\n");
        List<User> employees = userRepository.findAll();
        ExcelExportUtil.exportEmployeesToExcel(employees, response);
        // 记录导出日志
        operateLogService.recordExportLog(currentUser, employees.size(), request);
        System.out.println("\n==================================");
        System.out.println("||                              ||");
        System.out.println("||        结束导出            ||");
        System.out.println("||                              ||");
        System.out.println("==================================\n");
    }
}
